package com.knxhd.controller;

import com.knxhd.pojo.LlmResponse;
import com.knxhd.service.ChatModelService;
import io.modelcontextprotocol.client.McpAsyncClient;
import io.modelcontextprotocol.spec.McpSchema;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.StreamingChatModel;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Map;

/**
 * Author: tianluhua tianlh@qdcares.cn
 * Date: 2025-07-19 19:19:32
 * Description: 
 */
@RestController
@RequestMapping(value = "/chat")
@RequiredArgsConstructor
@Slf4j
public class ChatModelController {

    private final ChatModel chatModel;

    private final StreamingChatModel streamingChatModel;

    private final ChatModelService chatModelService;

    private final List<McpAsyncClient> mcpAsyncClients;

    @GetMapping(value = "/hello")
    public String hello(String query) {
        return chatModel.call(query);
    }

    @GetMapping(value = "/completions", produces = {MediaType.TEXT_EVENT_STREAM_VALUE})
    public Flux<LlmResponse> completions(String query) {
        return chatModelService.completions(query);
    }

    @RequestMapping("/test")
    public Mono<McpSchema.CallToolResult> test() {
        var mcpClient = mcpAsyncClients.get(0);

        return mcpClient.listTools()
                .flatMap(tools -> {
                    log.info("tools: {}", tools);

                    return mcpClient.callTool(
                            new McpSchema.CallToolRequest("maps_weather",  Map.of("city", "北京"))
                    );
                });
    }

}
